package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import com.tanhua.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(path = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 用户登录-发送验证码
     * @param param
     * @return
     */
    @PostMapping("login")
    public ResponseEntity login(@RequestBody Map<String,String> param){
        //1. 获取手机号
        String phone = param.get("phone");
        //2. 发送验证码
        userService.sendCode(phone);
        //3. 返回数据
        return ResponseEntity.ok(null);
        //return ResponseEntity.status(500).body("出错啦");
    }

    /**
     * 校验登录
     * @param map
     * @return
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map) {
        //1 调用map集合获取请求参数
        String phone = (String) map.get("phone");
        String code = (String) map.get("verificationCode");
        //2 调用userService完成用户登录
        Map retMap = userService.loginVerification(phone,code);
        //3 构造返回
        return ResponseEntity.ok(retMap);
    }

    /**
     * 保存用户信息
     *      *   UserInfo
     *      *   请求头中携带token
     * @param userInfo
     * @param token
     * @return
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token){
        //2、向userinfo中设置用户id
        userInfo.setId(UserHolder.getUserId());
        //3、调用service
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 上传用户头像
     * @param headPhoto
     * @param token
     * @return
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto,@RequestHeader("Authorization") String token) throws IOException {
        //2、向userinfo中设置用户id
        //3、调用service
        userInfoService.updateHead(headPhoto,UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }
}
